import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { Index } from '../../../apis/index';
import util from "../../../utils/util";
import { openBluetoothAdapterPeripheral } from '../../../utils/bluetooth';
const app = getApp();
const API = new Index();
let computeOrderCostTime = null;
WXPage({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    contentHeight: 0,
    listdata: [],
    //数据
    pageNum: 1,
    pageSize: 10,
    showMoreVisable: false,
    loginInfo: {},
    imageUrl: `${app.globalData.imageUrl}`
  },
  onLoad: async function (options) {
    this.setData({
      // contentHeight: app.globalData.windowH - 88 *app.globalData.windowW /750
      contentHeight: app.globalData.windowH - this.data.CustomBar - 130,
      loginInfo: wx.getStorageSync('login_key')
    });
    if (!this.data.loginInfo) {
      // 登录
      await API.getLoginToken().then(res => {
        this.setData({
          loginInfo: res.result
        });
        wx.setStorageSync("login_key", res.result);
      });
    }
  },
  // 计算订单时长与费用
  computeOrderCost(list) {
    let clearIntervalOff = true;
    for (let item of list) {
      let t = '0秒';
      let money = 0;
      if (item.state === 2) {
        let timeLen = parseInt((new Date().getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
        if (item.feeMode === 1) {
          money = item.priceTypeInfo.payIntervalPrice / (item.priceTypeInfo.payInterval * 60) * timeLen;
          if (money > item.priceTypeInfo.maxPayPrice) money = item.priceTypeInfo.maxPayPrice;
          money = (money / 100).toFixed(2);
        } else money = (item.priceTypeInfo.useDuration / 100).toFixed(2);
        clearIntervalOff = false;
      } else if (item.state === 5) {
        let timeLen = parseInt((new Date(item.endAt.replace(/\-/g, '/')).getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
      }
      item.useTime = t;
      if (money) item.settlementMoneyStr = money;
    }
    clearInterval(computeOrderCostTime);
    if (!clearIntervalOff) computeOrderCostTime = setInterval(ev => this.computeOrderCost(list), 1000);
    this.setData({
      listdata: list
    });
  },
  // 计算订单时长与费用
  computeOrderCost(list) {
    let clearIntervalOff = true;
    for (let item of list) {
      let t = '0秒';
      let money = 0;
      if (item.state === 2) {
        let timeLen = parseInt((new Date().getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
        if (item.feeMode === 1) {
          money = item.priceTypeInfo.payIntervalPrice / (item.priceTypeInfo.payInterval * 60) * timeLen;
          if (money > item.priceTypeInfo.maxPayPrice) money = item.priceTypeInfo.maxPayPrice;
          money = (money / 100).toFixed(2);
        } else money = (item.priceTypeInfo.useDuration / 100).toFixed(2);
        clearIntervalOff = false;
      } else if (item.state === 5) {
        let timeLen = parseInt((new Date(item.endAt.replace(/\-/g, '/')).getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
      }
      item.useTime = t;
      if (money) item.settlementMoneyStr = money;
    }
    clearInterval(computeOrderCostTime);
    if (!clearIntervalOff) computeOrderCostTime = setInterval(ev => this.computeOrderCost(list), 1000);
    this.setData({
      listdata: list
    });
  },
  getOrderList: function (pageNum) {
    var param = {
      pageNo: pageNum,
      pageSize: this.data.pageSize,
      tradeStatus: 2
    };
    if (param.pageNo === 1) this.data.listdata = [];
    API.getOrderList(param).then(res => {
      // if (param.pageNo === 1 && (res.result.data || []).length === 0) this.getHistory()
      var listData = this.data.listdata.concat(res.result.data);
      var showMore = false;
      if (res.result.totalCount > listData.length) {
        showMore = true;
      }
      this.computeOrderCost(listData);
      this.setData({
        listdata: listData,
        showMoreVisable: showMore
      });
    });
  },
  openDetail: function (ev) {
    let orderInfo = ev.mark.orderInfo;
    wx.navigateTo({
      url: '/pages/mine/orderdetail/orderdetail?tradeNo=' + orderInfo.tradeNo
    });
  },
  // 蓝牙通知
  openBluetoothAdapterPeripheral(targetPowerMinute) {
    openBluetoothAdapterPeripheral({
      bluetoothMac: app.globalData.bluetoothMac,
      powerMinute: targetPowerMinute,
      success: res => {
        console.log('startAdvertising', res);
      }
    });
  },
  // 结束订单，结束使用
  closeOrder: function (ev) {
    let orderInfo = ev.mark.orderInfo;
    let loginInfo = wx.getStorageSync('login_key');
    wx.showModal({
      title: '小电温馨提示',
      content: '安全用电提醒：充电完毕后，请记得切断电源，将充电线放回方盒。它安全、您安心！充一次、美一次!',
      cancelText: '继续使用',
      confirmText: '立即归还',
      cancelColor: '#666',
      confirmColor: '#00A49AFF',
      success: res => {
        if (!res.confirm) return;
        let param = {
          "deviceSn": orderInfo.deviceSn,
          "productId": orderInfo.productId,
          "openid": loginInfo.openid,
          "tradeNo": orderInfo.tradeNo
        };
        API.closeOrder(param).then(res => {
          if (app.globalData.bluetoothMac) this.openBluetoothAdapterPeripheral(1);
          wx.redirectTo({
            url: '/pages/mine/orderdetail/orderdetail?tradeNo=' + orderInfo.tradeNo
          });
        });
      }
    });
  },
  // 显示更多
  showMore: function () {
    var pageNum = this.data.pageNum + 1;
    this.getOrderList(pageNum);
  },
  onShow: function () {
    this.getOrderList(this.data.pageNum);
  },
  onHide: function () {
    clearInterval(computeOrderCostTime);
  },
  onUnload: function () {
    clearInterval(computeOrderCostTime);
  },
  getHistory: function () {
    wx.navigateTo({
      url: '/pages/mine/history/history'
    });
  },
  toPadline: function () {
    wx.navigateTo({
      url: '/pages/padline/padline'
    });
  },
  // 订单异常
  toRepairs(ev) {
    let {
      deviceSn,
      tradeNo
    } = ev.mark;
    wx.navigateTo({
      url: `/pages/report/report?deviceSn=${deviceSn}&tradeNo=${tradeNo}`
    });
  }
});